package models

import (
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
)

type Permission struct {
	orm.Model
	PermName string `json:"perm_name"`
	//PermType      uint8  `json:"perm_type"`
	PermKey string `json:"perm_key"`
	Route   string `json:"route"`
	//FrontendRoute string `json:"frontend_route"`
	ParentID uint `json:"parent_id"`
	//Keepalive uint8 `json:"keepalive"`
	//Status uint8 `json:"status"`
	Sort int64 `json:"sort"`

	orm.SoftDeletes
	orm.Timestamps

	// 关联关系
	Roles []Role `json:"roles" gorm:"many2many:role_permissions;"`
}

func (r *Permission) TableName() string {
	return "permissions"
}

// GetRoles 获取拥有此权限的角色
func (p *Permission) GetRoles() ([]Role, error) {
	var roles []Role
	err := facades.Orm().Query().
		Table("roles").
		Join("role_permissions", "roles.id", "=", "role_permissions.role_id").
		Where("role_permissions.permission_id", p.ID).
		Find(&roles)
	return roles, err
}

// GetUsers 获取拥有此权限的用户
func (p *Permission) GetUsers() ([]User, error) {
	var users []User
	err := facades.Orm().Query().
		Table("users").
		Join("user_roles", "users.id", "=", "user_roles.user_id").
		Join("role_permissions", "user_roles.role_id", "=", "role_permissions.role_id").
		Where("role_permissions.permission_id", p.ID).
		Find(&users)
	return users, err
}
